<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Repository;

use Doctrine\ORM\EntityRepository;
use Goods\Entity\GoodsVirtual;
use function Doctrine\ORM\QueryBuilder;

class GoodsVirtualRepository extends EntityRepository
{
    /**
     * 获取虚拟商品数量
     * @param array $data
     * @return int|mixed|string
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findGoodsVirtualCount(array $data)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('COUNT(v.virtualGoodsId)')
            ->from(GoodsVirtual::class, 'v')
            ->where('v.goodsId = :goodsId')->setParameter('goodsId', $data['goodsId'])
            ->andWhere('v.virtualGoodsState = :virtualGoodsState')->setParameter('virtualGoodsState', $data['virtualGoodsState'])
            ->andWhere(
                $query->expr()->orX()
                    ->add($query->expr()->eq('v.virtualGoodsEndTime', 0))
                    ->add($query->expr()->andX($query->expr()->gt('v.virtualGoodsEndTime', 0), $query->expr()->gte('v.virtualGoodsEndTime', time())))
            );
        if (isset($data['orderId']) && $data['orderId'] > 0) $query->andWhere('v.orderId = :orderId')->setParameter('orderId', $data['orderId']);

        return (int) $query->getQuery()->getSingleScalarResult();
    }
}